package io.wins.vertx.core;

import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import redis.clients.jedis.Jedis;

public class CacheManager {

    private Jedis client;
    private final Logger logger = LoggerFactory.getLogger(CacheManager.class);

    public static CacheManager getInstance() {
        return CacheInstance.cacheManager;
    }

    static class CacheInstance {
        static CacheManager cacheManager = new CacheManager();
    }

    public void init(final JsonObject config) {
        if (config != null) {
            this.client = new Jedis(config.getString("host"), config.getInteger("port"));
            if (!"PONG".equals(this.client.ping())) {
                this.logger.error("Can not init redis client.");
            }
        } else {
            this.logger.error("Redis config undefined!");
        }
    }

    public void set(final String id, final String module, final JsonObject value) {
        this.client.set(module + "-" + id, value.toString());
    }

    public JsonObject get(final String id, final String module) {
        final String object = this.client.get(module + "-" + id);
        return new JsonObject(object);
    }

    public void remove(final String id, final String module) {
        this.client.del(module + "-" + id);
    }
}
